﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MakeItWeb.Framework;
using System.Security;
using System.Data;

namespace AllNations.UI
{
    public partial class BlogManager : MakeItWebPage
    {
        Guid _HtmlPageId;

        protected void Page_Load(object sender, EventArgs e)
        {
            Framework.EditorHelper.InitializeEditor(editorContent, string.Format("~/PageImages/{0}", Request.QueryString["HtmlPageId"]));
            btSaveBlog.Click += new EventHandler(btSaveBlog_Click);
            if (!IsPostBack)
            {
                if (Request.QueryString["View"] == "EditBlog")
                {
                    StoredProcArgs args = new StoredProcArgs();
                    args["pBlogId"] = new Guid(Request.QueryString["BlogId"]);
                    using (DataSet ds = GenericQry.GetDataSet("proc_cm_GetBlogEntry", args))
                    {
                        if (ds.Tables[0].Rows.Count == 0)
                            throw new ArgumentException("BlogId");

                        DataRow dr = ds.Tables[0].Rows[0];
                        hidBlogId.Value = ((Guid)dr["blog_id"]).ToString();
                        txtBlogTitle.Text = dr["title_txt"].ToString();
                        txtBlogSubtitle.Text = dr.IsNull("subtitle_txt") ? string.Empty : dr["subtitle_txt"].ToString();
                        editorContent.Content = dr["content_txt"].ToString();
                    }
                }
                else
                    hidBlogId.Value = Guid.NewGuid().ToString();
            }

            if (string.IsNullOrEmpty(CurrentUserName))
                throw new SecurityException();

            try
            {
                _HtmlPageId = new Guid(Request.QueryString["HtmlPageId"]);
            }
            catch (Exception)
            {
                throw new ArgumentException("Invalid page request.");
            }
        }

        void btSaveBlog_Click(object sender, EventArgs e)
        {
            StoredProcArgs args = new StoredProcArgs();
            args["pBlogId"] = new Guid(hidBlogId.Value);
            args["pHtmlPageId"] = _HtmlPageId;
            args["pTitleTxt"] = txtBlogTitle.Text.Trim();
            if (!string.IsNullOrEmpty(txtBlogSubtitle.Text.Trim()))
                args["pSubtitleTxt"] = txtBlogSubtitle.Text.Trim();
            args["pContentTxt"] = editorContent.Content.Trim();
            args["pUserName"] = CurrentUserName;
            GenericCud.ExecuteCud("proc_cm_SaveBlogEntry", args);

            ClientScript.RegisterStartupScript(GetType(), "OnLoad", "RefreshParentPage();", true);
        }
    }
}